//
//  DXViewController.m
//  BabyBluetoothAppDemo
//
//  Created by 戴义兴 on 2017/4/6.
//  Copyright © 2017年 刘彦玮. All rights reserved.
//

#import "DXViewController.h"
#import "DXBluetooh.h"

static NSString *const MacAdress = @"FE44EBA3E408";
static NSString *const readCharacterUUID = @"EEA2";
static NSString *const writeCharacterUUID = @"EEA1";


@interface DXViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tablew;
@property (nonatomic, strong) DXBluetooh *bluetooh;
@property (nonatomic, strong) NSMutableDictionary *postureDic;
@end

@implementation DXViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tablew];
    //    self.view.backgroundColor = [UIColor redColor];
    
    
    self.bluetooh = [DXBluetooh shareBabyBluetooth];
    [self.bluetooh startBluetoothService];
    __weak typeof(self) weakSelf = self;
    [self.bluetooh scanDeviceWithMacAdress:MacAdress readCharacterUUID:readCharacterUUID writeCharacterUUID:writeCharacterUUID notifiyBlock:^(NSData *data, NSError *error) {
        NSLog(@"收到的数据%@  %lu",data, (unsigned long)data.length);
        Byte *dataByte = (Byte *)[data bytes];
        
        //获取协议包头
        Byte headerTyte[1];
        memcpy(&headerTyte, &dataByte[0], 1);
        NSData *headerData = [[NSData alloc] initWithBytes:&headerTyte length:1];
        
        //协议包头
        Byte getDataType[1] = {0xFE};
        if (![headerData isEqualToData:[[NSData alloc] initWithBytes:getDataType length:1]]) {
            NSLog(@"接受包有问题");
            return ;
        }
        
        //获取协长度
        Byte lengthTyte[1];
        memcpy(&lengthTyte, &dataByte[1], 1);
        int length = (int)lengthTyte[0];
        if (length != data.length) {
            NSLog(@"包长度不对");
            return;
        }
        
        
        //获取协议种类
        Byte protocolTyte[1];
        memcpy(&protocolTyte, &dataByte[2], 1);
        if (protocolTyte[0] == 0xE1) {  // 同步时间应答
            //获取电量
            Byte battary[1];
            memcpy(&battary, &dataByte[3], 1);
            int battaryInt = (int)battary[0];
            NSLog(@"电池电量: %d", battaryInt);
            
            Byte motorVibration[1];
            memcpy(&motorVibration, &dataByte[4], 1);
            int motorVibrationInt = (int)motorVibration[0];
            NSLog(@"马达震动：%d", motorVibrationInt);
            
            //版本号
            NSInteger headerCount = 3 + 1 + 1;
            NSInteger versionCount = length - headerCount;
            Byte version[versionCount];
            memcpy(&version, &dataByte[headerCount], versionCount);
            
            NSMutableString *versionString= [[NSMutableString alloc] init];
            for (NSInteger i = 0; i < versionCount; i ++) {
                NSString *string = [NSString stringWithFormat:@"%c", version[i]]; // A
                [versionString appendString:string];
            }
            NSLog(@"版本号: %@",versionString);
            
            
            [weakSelf.bluetooh respondTimeToHardware];
        } else if (protocolTyte[0] == 0xE2) { // 同步记忆计步数据应答
            //时间+计步数据
            NSInteger timeAndStepsCount = length - 3;
            Byte timeAndSteps[timeAndStepsCount];
            memcpy(&timeAndSteps, &dataByte[3], timeAndStepsCount);
            NSData *timeAndStepData = [[NSData alloc] initWithBytes:timeAndSteps length:timeAndStepsCount];
            NSLog(@"同步记忆计步数据应答: %@",timeAndStepData);
            
            [weakSelf.bluetooh respondsynStep];
        } else if (protocolTyte[0] == 0xE3) { // 同步记忆坐姿数据flash应答
            
            //同步记忆坐姿数据flash
            NSInteger flashRecordCount = length - 3;
            Byte flashRecord[flashRecordCount];
            memcpy(&flashRecord, &dataByte[3], flashRecordCount);
            [self postureMosaic:flashRecord lenght:flashRecordCount];
            NSData *flashRecordData = [[NSData alloc] initWithBytes:flashRecord length:flashRecordCount];
            NSLog(@"同步记忆坐姿所有数据%@",data);
            NSLog(@"同步记忆坐姿数据（主动发起）: %@",flashRecordData);
            
            //            [weakSelf respondsynPosture];
        } else if (protocolTyte[0] == 0xE4) { // 交换结束应答
            NSLog(@"交换结束应答");
            [weakSelf.bluetooh respondComplete];
        } else if (protocolTyte[0] == 0xE5) { // 读取电池电量
            //获取电量
            Byte battary[1];
            memcpy(&battary, &dataByte[3], 1);
            int battaryInt = (int)battary[0];
            NSLog(@"获取电池电量: %d", battaryInt);
            
        } else if (protocolTyte[0] == 0xE6) { // 激活命令
            NSLog(@"激活指令生效");
        } else if (protocolTyte[0] == 0xE7) { // 取消激活命令
            NSLog(@"取消激活指令生效");
        } else if (protocolTyte[0] == 0xE8) { // 连接状态下同步计步数据
            //时间+计步数据
            NSInteger timeAndStepsCount = length - 3;
            Byte timeAndSteps[timeAndStepsCount];
            memcpy(&timeAndSteps, &dataByte[3], timeAndStepsCount);
            NSData *timeAndStepData = [[NSData alloc] initWithBytes:timeAndSteps length:timeAndStepsCount];
            NSLog(@"获取时间+计步数据: %@",timeAndStepData);
        } else if (protocolTyte[0] == 0xE9) { // 连接状态下同步坐姿数据
            //同步记忆坐姿数据flash
            NSInteger flashRecordCount = length - 3;
            Byte flashRecord[flashRecordCount];
            memcpy(&flashRecord, &dataByte[3], flashRecordCount);
            NSData *flashRecordData = [[NSData alloc] initWithBytes:flashRecord length:flashRecordCount];
            NSLog(@"获取同步记忆坐姿数据: %@",flashRecordData);
        } else if (protocolTyte[0] == 0xEA) { // 设置马达震动
            NSLog(@"设置马达震动成功");
        } else if (protocolTyte[0] == 0xEB) { // 读取马达震动
            Byte motorVibration[1];
            memcpy(&motorVibration, &dataByte[3], 1);
            int motorVibrationInt = (int)motorVibration[0];
            NSLog(@"读取马达震动 %d", motorVibrationInt);
        } else if (protocolTyte[0] == 0xEC) { // 效准坐姿
            NSLog(@"效准坐姿成功");
        }
        
    }wtiteData:^(BOOL ready) {
      
    } wtiteDataResult:^(NSData *value, NSError *error) {
        
    } readRSSIBlock:^(NSNumber *RSSI, NSError *error) {
        
    } failToConnectAtChannelBlock:^(NSError *error) {
        
    } disconnectAtChannelBlock:^(NSError *error) {
        
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//拼接坐姿数据
- (void)postureMosaic:(Byte*)posture lenght:(NSUInteger)lenght {
    
    NSInteger frame;
    static NSInteger frameCount;
    static NSString *timeString;
    
    static NSMutableData *postureData;
    frame = posture[0];
    NSLog(@"第 %ld贞  共%ld", (long)frame, frameCount);
    
    if (frame == 0) {  //该天开始传输
        [self.postureDic removeAllObjects];
        
        NSInteger month = posture[1];
        NSInteger day = posture[2];
        frameCount = posture[4];
        timeString = [NSMutableString stringWithFormat:@"%ld月%ld日",(long)month, (long)day];
        
        postureData = [[NSMutableData alloc] init];
        
        NSMutableArray *status = [[NSMutableArray alloc] init];
        [self.postureDic setObject:status forKey:timeString];
    } else if(frame <= frameCount) { //该天传输过程
        
        Byte dataTyte[lenght - 1];
        memcpy(&dataTyte, &posture[1], lenght - 1);
        NSData *headerData = [[NSData alloc] initWithBytes:&dataTyte length:lenght - 1];
        [postureData appendData:headerData];
    }
    
    if(frame == frameCount) { //传输完该天
        NSMutableArray *status = [self.postureDic objectForKey:timeString];
        NSInteger statuCount = (postureData.length - 1) / 3;
        Byte *dataByte = (Byte *)[postureData bytes];
        for (NSInteger j = 0; j < statuCount; j ++) {
            NSDictionary *dic = @{@"hour": @(dataByte[j*3 ]), @"minute": @(dataByte[j*3 + 1]), @"status": @(dataByte[j*3 + 2])};
            [status addObject:dic];
        }
        NSLog(@"当前时间 %@", self.postureDic.allKeys.firstObject);
        NSLog(@"2完全拼接好后的数据%@", self.postureDic);
        frameCount = 0;
        
        [self.bluetooh respondsynPosture];
    }
}
#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"读取电池电量";
            break;
        case 1:
            cell.textLabel.text = @"激活命令";
            break;
        case 2:
            cell.textLabel.text = @"取消激活命令";
            break;
        case 3:
            cell.textLabel.text = @"链接状态下同步计数数据";
            break;
        case 4:
            cell.textLabel.text = @"链接状态下同步坐姿数据";
            break;
        case 5:
            cell.textLabel.text = @"设置马达震动 open";
            break;
        case 6:
            cell.textLabel.text = @"设置马达震动 close";
            break;
        case 7:
            cell.textLabel.text = @"读取马达震动";
            break;
        case 8:
            cell.textLabel.text = @"校准坐姿";
            break;
        case 9:
            cell.textLabel.text = @"重启";
            break;
            
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击 %ld", (long)indexPath.row);
    switch (indexPath.row) {
        case 0:
            [self.bluetooh getBattary];
            break;
        case 1:
            [self.bluetooh activation];
            break;
        case 2:
            [self.bluetooh cancelActivation];
            break;
        case 3:
            [self.bluetooh synStep];
            break;
        case 4:
            [self.bluetooh synPosture];
            break;
        case 5:
            [self.bluetooh setMotor:YES shockTime:5];
            break;
        case 6:
            [self.bluetooh setMotor:NO shockTime:0];
            break;
        case 7:
            [self.bluetooh getMotor];
        case 8:
            [self.bluetooh setPosture];
            break;
        case 9:
            [self.bluetooh restart];
            break;
            
        default:
            break;
    }
}
#pragma mark - get tablew

- (UITableView *)tablew {
    if (_tablew == nil) {
        _tablew = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height - 100)];
        _tablew.delegate = self;
        _tablew.dataSource = self;
        _tablew.scrollEnabled = NO;
    }
    return _tablew;
}


- (NSMutableDictionary *)postureDic {
    if (_postureDic == nil) {
        _postureDic = [[NSMutableDictionary alloc] init];
    }
    return _postureDic;
}

@end
